﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Needed to get the FormsAuthenticationTicket
using System.Web.Security;
using AmkeniCrossLoginApplication.Data_Access;
using AmkeniCrossLoginApplication.Classes;

namespace AmkeniCrossLoginApplication.Account
{
    public partial class Login : Security
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (User.Identity.IsAuthenticated)
                {
                    if (string.IsNullOrEmpty(Request["ReturnUrl"]))
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                    //else
                    //{
                    //    Response.Redirect("../../Amkeni_System/AccessDenied.aspx");
                    //}
                }
            }

            //FormsIdentity cIdentity = Page.User.Identity as FormsIdentity;
            //if (cIdentity != null)
            //{
            //    this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName;
            //    this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket);
            //}
        }

        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        private bool ValidateUser(string userName, string passWord)
        {
            string enteredPassword = null;
            try
            {
                string pWord = (from data in db.users
                                where
                                    data.email == userName
                                select data.password).FirstOrDefault();

                enteredPassword = base64Decode(pWord);
            }
            catch (Exception ex)
            {
                //throw new Exception("Login Error "+ex.Message+" "+ex.StackTrace);
                Error.Visible = true;
                //Error.Text = "Provide your correct credentials " + ex.Message + ex.StackTrace;
                Error.Text = "Provide your correct credentials"+ ex.Message;
            }

            // If no password found, return false.
            if (enteredPassword == null)
            {
                // You could write failed login attempts here to event log for additional security.
                return false;
            }

            // Compare enteredpassword and input passWord, using a case-sensitive comparison.
            return (0 == string.Compare(enteredPassword, passWord, false));
        }



        protected void LogInButton_Click(object sender, EventArgs e)
        {
            if (ValidateUser(Username.Text.Trim(), Password.Text.Trim()))
            {
                string roles;

                string uEmail = Username.Text.Trim();
                string uPword = base64Encode(Password.Text.Trim());
                FormsAuthentication.Initialize();

                try
                {
                    var userRole = (from data in db.users
                                    where
                                        data.email == uEmail &&
                                        data.password == uPword
                                    select new
                                    {
                                        data.roles,
                                        data.active
                                    }).FirstOrDefault();

                    if (userRole.active == false)
                    {
                        Error.Visible = true;
                        Error.Text = "Sorry you have been deactivated. Please contact the system administrator.";
                        return;
                    }

                    roles = userRole.roles.Trim();

                }
                catch (Exception ex)
                {
                    throw new Exception("Login Error " + ex.Message + " " + ex.StackTrace);
                    //Label2.Text = "Login Error " + ex.Message + " " + ex.StackTrace;
                }
                FormsAuthenticationTicket ticket;
                string hashedCookieString;
                HttpCookie cookie;

                //Create a new ticket used for authentication
                ticket = new FormsAuthenticationTicket(
                    1, //Ticket version
                    uEmail.Trim(), //Username associated with the ticket
                    DateTime.Now, //Date issued
                    DateTime.Now.AddMinutes(120), //Date/Time to expire
                    PersistCookie.Checked, //Persistant User cookie
                    roles, //Custom data i.e user role
                    FormsAuthentication.FormsCookiePath //Path for the ticket when stored in a cookie
                    );

                //Encrypt the cookie using the machine key for secure transport
                hashedCookieString = FormsAuthentication.Encrypt(ticket);

                cookie = new HttpCookie(
                    FormsAuthentication.FormsCookieName, //Name of authentication cookie
                    hashedCookieString //Encrypted ticket
                    );

                // Set the cookie's expiration time to the tickets expiration time
                if (PersistCookie.Checked)
                {
                    cookie.Expires = ticket.Expiration;
                }

                // Add the cookie to the list for outgoing response
                Response.Cookies.Add(cookie);

                //Record the Login date for the user
                user logginInUser = db.users.FirstOrDefault(
                                            data => data.email == uEmail);
                if (logginInUser != null)
                {
                    logginInUser.login_date = DateTime.Now;
                    db.SaveChanges();
                }


                // Redirect to requested URL, or homepage if no previous page requested
                //string returnURL = Request.QueryString["ReturnUrl"].Trim();
                if (string.IsNullOrEmpty(Request["ReturnUrl"]))
                {
                    Response.Redirect("~/Default.aspx");
                }
                Response.Redirect(Request.QueryString["ReturnUrl"].Trim(), true);
                //Response.Redirect(FormsAuthentication.GetRedirectUrl(uEmail,true));

            }
            else
            {
                Error.Visible = true;
                Error.Text = "Provide your correct credentials......";
            }
        }

        protected void ForgotButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Account/Forgot.aspx", true);
        }
    }
}